import { useRef, useState } from 'react'

export function useTableHeight() {
  const tableDom = useRef<HTMLDivElement>(null)
  const [tableScrollHeight, setTableScrollHeight] = useState(400)

  function getTableHeight(extraHeight: number) {
    const tableBodyHeight = calcTableBodyHeight()
    const tableHeight = tableBodyHeight - extraHeight - 30
    setTableScrollHeight(tableHeight)
    return tableHeight
  }

  function setTableHeight(extraHeight: number) {
    if (tableDom.current) {
      const tableBodyDom = tableDom.current.querySelector('.ant-table') as HTMLElement
      if (tableBodyDom) {
        tableBodyDom.style.height = `${getTableHeight(extraHeight)}px`
      }
    }
  }

  function calcTableBodyHeight() {
    if (tableDom.current) {
      const tablePB = 16

      /** 搜索框高度 */
      let tableSearchHeight = 0
      const tableSearchMb = 16
      const tableSearchElm = tableDom.current.querySelector('.ant-pro-table-search') as HTMLElement
      const tableSearchSize = tableSearchElm?.getBoundingClientRect()

      tableSearchHeight = tableSearchSize?.height || -tableSearchMb

      /** 工具栏高度 */
      let tableToolHeight = 0
      const tableToolElm = tableDom.current.querySelector(
        '.ant-pro-table-list-toolbar'
      ) as HTMLElement
      const tableToolSize = tableToolElm?.getBoundingClientRect()
      tableToolHeight = tableToolSize?.height || 0

      /** 表头高度 */
      let tableHeaderHeight = 0
      const tableHeaderElm = tableDom.current.querySelector('.ant-table-thead') as HTMLElement
      const tableHeaderSize = tableHeaderElm?.getBoundingClientRect()
      tableHeaderHeight = tableHeaderSize?.height || 0

      /** 表格底部翻页器高度 */
      let tablePaginationHeight = 0
      const tablePaginationMt = 16
      const tablePaginationElm = tableDom.current.querySelector('.ant-pagination') as HTMLElement
      const tablePaginationSize = tablePaginationElm?.getBoundingClientRect()
      tablePaginationHeight = tablePaginationSize?.height || 0

      const tableBodyHeight =
        window.innerHeight -
        tableSearchHeight -
        tableHeaderHeight -
        tableToolHeight -
        tablePaginationHeight -
        tablePB -
        tableSearchMb -
        tablePaginationMt
      return tableBodyHeight
    }

    return 0
  }

  return {
    tableDom,
    tableScrollHeight,
    setTableHeight
  }
}
